﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IPC.Communication.Core.Address
{
    public class ModbusAddress : DeviceAddressBase
    {
        public int Station
        {
            get;
            set;
        }

        public int Function
        {
            get;
            set;
        }

        public ModbusAddress()
        {
            Station = -1;
            Function = -1;
            base.Address = 0;
        }

        public ModbusAddress(string address)
        {
            Station = -1;
            Function = -1;
            base.Address = 0;
            Parse(address);
        }

        public ModbusAddress(string address, byte function)
        {
            Station = -1;
            Function = function;
            base.Address = 0;
            Parse(address);
        }

        public ModbusAddress(string address, byte station, byte function)
        {
            Station = -1;
            Function = function;
            Station = station;
            base.Address = 0;
            Parse(address);
        }

        public override void Parse(string address)
        {
            if (address.IndexOf(';') < 0)
            {
                base.Address = ushort.Parse(address);
                return;
            }
            string[] array = address.Split(';');
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i][0] == 's' || array[i][0] == 'S')
                {
                    Station = byte.Parse(array[i].Substring(2));
                }
                else if (array[i][0] == 'x' || array[i][0] == 'X')
                {
                    Function = byte.Parse(array[i].Substring(2));
                }
                else
                {
                    base.Address = ushort.Parse(array[i]);
                }
            }
        }

        public ModbusAddress AddressAdd(int value)
        {
            return new ModbusAddress
            {
                Station = Station,
                Function = Function,
                Address = (ushort)(base.Address + value)
            };
        }

        public ModbusAddress AddressAdd()
        {
            return AddressAdd(1);
        }

        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (Station >= 0)
            {
                stringBuilder.Append("s=" + Station.ToString() + ";");
            }
            if (Function == 2 || Function == 4)
            {
                stringBuilder.Append("x=" + Function.ToString() + ";");
            }
            stringBuilder.Append(base.Address.ToString());
            return stringBuilder.ToString();
        }
    }
}
